﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace testMobi
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Page
    {

        private XDocument _doc;
        public XDocument doc
        {
            get
            {
                if(_doc==null)
                    _doc=((App)Application.Current).Doc;

                return _doc;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            BindAllCountries(0);
           
        }

        public void BindAllCountries(int idParent)
        {
            

            string s=System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"countrylist.xml");
            //this is used when teting application - not to wait for downloading each time
            //XDocument doc = XDocument.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"countrylist.xml"));
           
            IEnumerable<XElement> data = doc.Element("countries").Elements("country").Where(p => p.Attribute("idParent").Value == idParent.ToString()).OrderBy(p => p.Attribute("name").Value);
            int count = data.Count();
            if (count > 0)
                lstCountries.DataContext = data;

            if (idParent > 0 && count > 0)
                btnNavigateAllCountries.Visibility = System.Windows.Visibility.Visible;
            else
                btnNavigateAllCountries.Visibility = System.Windows.Visibility.Hidden;

        }

        private void lstCountries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            XElement element = lstCountries.SelectedItem as XElement;

            if (element != null)
            {
                int id = Int32.Parse(element.Attribute("id").Value);
                int idParent = Int32.Parse(element.Attribute("idParent").Value);
                if (idParent == 0)
                {
                   
                    BindAllCountries(id);
                }
                
            }
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            MenuPage page = new MenuPage();
            NavigationService nav = NavigationService.GetNavigationService(this);
            nav.Navigate(page);
        }

        private void btnNavigateAllCountries_Click(object sender, RoutedEventArgs e)
        {
            BindAllCountries(0);
        }

        
    }
}
